<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '128M');

$g_start = microtime(true);
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
$dbconn = Connection::getInstance();

$s2scams = getS2sCams($dbconn);
if(count($s2scams)>0){
	sendS2sCam($s2scams, $dbconn);
}

echo "\n". (microtime(true)-$g_start) . " seconds\n";



function getS2sCams(Connection $db)
{
	$sql = " SELECT * FROM s2scam WHERE status='unfired' limit 2";
	try{
		$result = $db->query($sql);
		return $result;
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function sendS2sCam($s2scams, Connection $db)
{
	foreach($s2scams as $s2scam){
		$parseUrl = parse_url($s2scam['sendurl']);
		$querys = array();
		foreach(explode('&', $parseUrl['query']) as $k=>$q) {
  			list($varname, $value) = explode('=', $q);
  			$querys[$varname] = $value;
		}
		if($querys['affiliateID'] == '75'){
			if(time() - $s2scam['created'] < 0){
				//var_dump(date('Y-m-d H:i:s', $s2scam['created']));
				continue;
			}
		}
		
		
		$ch = curl_init();
		if($s2scam['sendmethod'] == 'post'){
			curl_setopt($ch, CURLOPT_POST, 1);
			list($url, $params) = explode('?', $s2scam['sendurl']);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		}else{
			$url = $s2scam['sendurl'];
		}
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		
		$content = curl_exec($ch);
print_r($content);
		if(strtolower(trim($content)) == 'tracked'){
			setStatus(array( $s2scam['id'] ), 'fired', $db);
		}else{
			setStatus(array( $s2scam['id'] ), 'fire_failed', $db);
		}
	}
}

function setStatus($ids, $status, Connection $db)
{
	$sql = " UPDATE s2scam SET status=?, fire_date=? WHERE id IN ( " . implode(', ', $ids) . " ) ";
	try{
		$result = $db->execute($sql, array( $status, date('Y-m-d') ));
		return $result;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

	
	
	
	
	
	
	